package com.example.administrator.music;

import android.animation.ObjectAnimator;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.AudioManager;
import android.media.MediaMetadataRetriever;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.annotation.RequiresApi;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.LinearInterpolator;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.QueryListener;
import cn.bmob.v3.listener.UpdateListener;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private ViewPager mpager;
    private List<View> mlist = new ArrayList<View>();
    private View view1,view2,view3;
    private PagerAdapter madapter;
    private ListView listView;
    private ArrayList<Music> musiclist;
    private ImageView view, head, sel;
    private TextView timenow, time, songname, artname;
    private SeekBar Seekbar, shengyin;
    private boolean star = false;
    private RelativeLayout laytop;
    private AudioManager am;
    public static int theme = 101;
    public static int playmode = 201;
    private boolean begin=true;
    private boolean Zhuc = false;
    public static  String iconimg="10";


    //歌词界面
    private LinearLayout linearLayout, main_bg;
    private TextView tv_lrc;
    private String lrc_data = null;
    private AsyncDownLoad asyncDownLoad;
    private String musicname = null;
    private String filename = null;


    private int duration, seekbartime;
    private int number = 0;
    private int status = 2;

    private Handler handler = new Handler();
    private ImageView previous, play, stop, next;
    private StatusChangedReceiver receiver;
    private static final int PROGRESS_INCREASE = 0;
    private static final int PROGRESS_PAUSE = 1;
    private static final int PROGRESS_RESET = 2;

    //旋转图片
    private ObjectAnimator mCircleAnimator;
    private ImageView mCircle;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initlistdemoView();
        listview();
        bindStaatusChingedRecevier();
        initSeekBarHandler();
        setsound(shengyin);
        startService(new Intent(this, MusicService.class));
        status = MusicService.COMMAND_STOP;
        Bmob.initialize(this, "6aeb83da9239b94d7c6773a50f22c5d3");
        mpager.setCurrentItem(1);
        setText();
    }

    @Override
    protected void onResume() {
        super.onResume();
        File file2 = new File("/data/data/com.example.administrator.music/files/musicuserobjectId");
        if (file2.exists()) {
            String id = load("musicuserobjectId").trim();
            BmobQuery<MusicPlayUser> user = new BmobQuery<MusicPlayUser>();
            user.getObject(id, new QueryListener<MusicPlayUser>() {
                @Override
                public void done(MusicPlayUser musicPlayUser, BmobException e) {
                    if (e == null) {
                       /* Toast.makeText(MainActivity.this, "查询成功：用户名：" + musicPlayUser.getUsername()
                                + "密码：" + musicPlayUser.getPassword(), Toast.LENGTH_SHORT).show();*/
                        theme = musicPlayUser.getTheme();
                        setbgtheme(theme);
                        playmode=musicPlayUser.getMode();
                        iconimg=musicPlayUser.getIconimage();
                        Zhuc = true;
                        if (begin) {
                            number = musicPlayUser.getSong();
                            sendBroadcastOnCommand(MusicService.COMMAND_BEGIN);
                            begin=false;
                        }
                        Toast.makeText(MainActivity.this, "登陆成功", Toast.LENGTH_SHORT).show();
                    } else {
                        String e1 = String.valueOf(e);
                        Toast.makeText(MainActivity.this, e1, Toast.LENGTH_SHORT).show();
                    }
                }
            });

        } else {
            Zhuc = false;
        }

    }


    //保存数据
    @Override
    protected void onPause() {
        super.onPause();
        File file2 = new File("/data/data/com.example.administrator.music/files/musicuserobjectId");
        if (file2.exists()) {
            MusicPlayUser user = new MusicPlayUser();
            String id=load("musicuserobjectId").trim();
            user.setTheme(theme);
            user.setMode(playmode);
            user.setSong(number);
            user.update(id, new UpdateListener() {
                @Override
                public void done(BmobException e) {
                }
            });
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);//注销广播
        if (asyncDownLoad != null && !asyncDownLoad.isCancelled()) {
            asyncDownLoad.cancel(true);
        }
    }

    //注册广播接收器
    private void bindStaatusChingedRecevier() {
        receiver = new StatusChangedReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(MusicService.BROADCAST_MUSICSERVICE_UPDATE_STATUS);
        filter.addAction("android.media.VOLUME_CHANGED_ACTION");//添加对物理键控制声音的广播接收
        filter.addAction(MenuActivity.BROADCAST_MENUACTIVITY_CONTROL);
        filter.addAction(MenuActivity.BROADCAST_MENUMODE_CONTROL);
        registerReceiver(receiver, filter);
    }

    private void initView() {
        mpager = (ViewPager) findViewById(R.id.viewPager);
        laytop = (RelativeLayout) findViewById(R.id.linearlayouttop);
        shengyin = (SeekBar) findViewById(R.id.shengyin);
        head = (ImageView) findViewById(R.id.head);
        sel = (ImageView) findViewById(R.id.sel);
        main_bg = (LinearLayout) findViewById(R.id.main_bg);
        //把页面转化为视图，等着加载到主页面中
        LayoutInflater mlayout = LayoutInflater.from(this);
        view1 = mlayout.inflate(R.layout.lyric, null);
        view2 = mlayout.inflate(R.layout.songitem, null);
        view3 = mlayout.inflate(R.layout.circleimage,null);

        //歌曲时间
        timenow = (TextView) findViewById(R.id.timenow);
        time = (TextView) findViewById(R.id.time);
        //进度条
        Seekbar = (SeekBar) findViewById(R.id.seekbar);
        //4个播放状态控制按钮
        play = (ImageView) findViewById(R.id.play);
        previous = (ImageView) findViewById(R.id.previous);
        stop = (ImageView) findViewById(R.id.stop);
        next = (ImageView) findViewById(R.id.next);
        //歌曲信息
        songname = (TextView) findViewById(R.id.songname);
        artname = (TextView) findViewById(R.id.artname);

        previous.setOnClickListener(this);
        play.setOnClickListener(this);
        stop.setOnClickListener(this);
        next.setOnClickListener(this);
        head.setOnClickListener(this);
        sel.setOnClickListener(this);


        //进度条监听控制
        Seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if (status == MusicService.STATUS_PLAYING) {
                    Seekbar.setProgress(seekBar.getProgress());
                    sendBroadcastOnCommand(MusicService.COMMAND_SEEK_TO);
                    seekbartime = seekBar.getProgress();
                }
            }
        });
        //转动页面添加视图
        mlist.add(view2);
        mlist.add(view3);
        mlist.add(view1);
        madapter = new PagerAdapter() {

            @Override
            public Object instantiateItem(ViewGroup container, int position) {
                View view=mlist.get(position);
                container.addView(view);
                return view;
            }

            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                container.removeView(mlist.get(position));
            }

            @Override
            public int getCount() {
                return mlist.size();
            }

            @Override
            public boolean isViewFromObject(View view, Object object) {
                return view==object;
            }
        };
        mpager.setAdapter(madapter);
        //视图滑动监听
        mpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }
            @Override
            public void onPageSelected(int position) {
                int item = position;
                if (item==0){
                    listView.setSelection(number);
                }
            }
            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        //3个视图页面中的控件注册
        listView = (ListView) view2.findViewById(R.id.songitem_listview);
        tv_lrc = (TextView) view1.findViewById(R.id.gechi);
        linearLayout = (LinearLayout) view1.findViewById(R.id.linearlayout1);
        tv_lrc.setText("当前没有播放的歌曲");
        mCircle= (ImageView) view3.findViewById(R.id.circle);
        mCircleAnimator = ObjectAnimator.ofFloat(mCircle, "rotation", 0.0f, 360.0f);
        mCircleAnimator.setInterpolator(new LinearInterpolator());
        //设置旋转速度
        mCircleAnimator.setDuration(4000);
        //旋转次数 -1表示一直旋转
        mCircleAnimator.setRepeatCount(-1);
        //设置旋转完了之后继续旋转
        mCircleAnimator.setRepeatMode(ObjectAnimator.RESTART);
    }

    //将音乐添加到数组中的函数
    private void initlistdemoView() {
        musiclist = Musiclist.getMusiclist();
        //避免重复添加音乐
        if (musiclist.isEmpty()) {
            Cursor mMusicCursor = this.getContentResolver().query(
                    MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null,
                    MediaStore.Audio.AudioColumns.TITLE);
            //标题
            int indexTitle = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.TITLE);
            //艺术家
            int indexArtist = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.ARTIST);
            //总时长
            int indexTotalTime = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.DURATION);
            //路径
            int indexPath = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.DATA);

            /**通过mMusicCursor游标遍历数据库，并将Music类对象加载到ArrayList中*/
            for (mMusicCursor.moveToFirst(); !mMusicCursor.isAfterLast(); mMusicCursor
                    .moveToNext()) {
                String strTitle = mMusicCursor.getString(indexTitle);
                String strArtist = mMusicCursor.getString(indexArtist);
                String strTotoalTime = mMusicCursor.getString(indexTotalTime);
                String strPath = mMusicCursor.getString(indexPath);

                if (strArtist.equals("<unknown>"))
                    strArtist = "无艺术家";
                Music music = new Music(strTitle, strArtist, strPath, strTotoalTime);
                musiclist.add(music);
            }
        }
    }

    //将数组中的音乐通过简单适配器加载到list view中
    private void listview() {
        List<Map<String, String>> listmap = new ArrayList<Map<String, String>>();
        HashMap<String, String> map;
        SimpleAdapter simpleAdapter;
        for (Music music : musiclist) {
            map = new HashMap<String, String>();
            map.put("musicName", music.getMusicName());
            map.put("musicArtist", music.getMusicArtist());
            listmap.add(map);
        }
        String[] from = new String[]{"musicName", "musicArtist"};
        int[] to = {R.id.listview_songname, R.id.listview_artname};
        simpleAdapter = new SimpleAdapter(this, listmap, R.layout.listviewdemo, from, to);
        listView.setAdapter(simpleAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                number = position;
                sendBroadcastOnCommand(MusicService.COMMAND_PLAY);
            }
        });
    }

    //可被调用的发送广播的函数
    private void sendBroadcastOnCommand(int command) {
        Intent intent = new Intent(MusicService.BROADCAST_MUSICSERVICE_CONTROL);
        intent.putExtra("command", command);
        switch (command) {
            case MusicService.COMMAND_PLAY:
                intent.putExtra("number", number);
                break;
            case MusicService.COMMAND_SEEK_TO:
                intent.putExtra("time", Seekbar.getProgress());
                break;
            case MusicService.COMMAND_BEGIN:
                intent.putExtra("number",number);
                break;
            case MusicService.COMMAND_PREVIOUS:
            case MusicService.COMMAND_NEXT:
            case MusicService.COMMAND_PAUSE:
            case MusicService.COMMAND_STOP:
            case MusicService.COMMAND_RESUME:
            default:
                break;
        }
        sendBroadcast(intent);
    }

    //接收广播的类
    class StatusChangedReceiver extends BroadcastReceiver {

        @RequiresApi(api = Build.VERSION_CODES.KITKAT)
        @Override
        public void onReceive(Context context, Intent intent) {
            //对物理键控制音量的监听事件反应
            if (intent.getAction().equals("android.media.VOLUME_CHANGED_ACTION")) {
                int sound = am.getStreamVolume(AudioManager.STREAM_MUSIC);
                shengyin.setProgress(sound);
            }
            if (intent.getAction().equals(MenuActivity.BROADCAST_MENUACTIVITY_CONTROL)) {
                theme = intent.getIntExtra("theme", 101);
                setbgtheme(theme);
            }
            if (intent.getAction().equals(MenuActivity.BROADCAST_MENUMODE_CONTROL)){
                playmode=intent.getIntExtra("mode",201);
            }
            if (intent.getAction().equals(MusicService.BROADCAST_MUSICSERVICE_UPDATE_STATUS)) {
                status = intent.getIntExtra("status", -1);
                switch (status) {
                    case MusicService.STATUS_PLAYING:
                        handler.removeMessages(PROGRESS_INCREASE);
                        seekbartime = intent.getIntExtra("time", 0);
                        duration = intent.getIntExtra("duration", 0);
                        timenow.setText(formatTime(seekbartime));
                        time.setText(formatTime(duration));
                        songname.setText(intent.getStringExtra("musicnName"));
                        artname.setText(intent.getStringExtra("musicArtist"));
                        number = intent.getIntExtra("number", number);
                        Seekbar.setMax(intent.getIntExtra("duration", 0));
                        handler.sendEmptyMessageDelayed(PROGRESS_INCREASE, 0);
                        play.setImageResource(R.drawable.pause);
                        //歌词设置
                        musicname = intent.getStringExtra("musicnName");
                        try {
                            get_lrc(MainActivity.this);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        break;
                    case MusicService.STATUS_PAUSED:
                        number = intent.getIntExtra("number", number);
                        handler.sendEmptyMessage(PROGRESS_PAUSE);
                        play.setImageResource(R.drawable.play);
                        break;

                    case MusicService.STATUS_STOPPED:
                        seekbartime = 0;
                        duration = 0;
                        timenow.setText(formatTime(seekbartime));
                        time.setText(formatTime(duration));
                        handler.sendEmptyMessage(PROGRESS_RESET);
                        play.setImageResource(R.drawable.play);
                        break;
                    case MusicService.STATUS_BEGIN:
                        seekbartime = intent.getIntExtra("time", 0);
                        duration = intent.getIntExtra("duration", 0);
                        timenow.setText(formatTime(seekbartime));
                        time.setText(formatTime(duration));
                        songname.setText(intent.getStringExtra("musicnName"));
                        artname.setText(intent.getStringExtra("musicArtist"));
                        number = intent.getIntExtra("number", number);
                        play.setImageResource(R.drawable.play);
                        break;
                    case MusicService.STATUS_COMPLETED:
                        switch (playmode) {
                            case 201:
                                number = intent.getIntExtra("number", 0);
                                if (number == Musiclist.getMusiclist().size() - 1) {
                                    sendBroadcastOnCommand(MusicService.COMMAND_STOP);
                                } else {
                                    sendBroadcastOnCommand(MusicService.COMMAND_NEXT);
                                }
                                handler.sendEmptyMessage(PROGRESS_RESET);
                                play.setImageResource(R.drawable.play);
                                break;
                            case 202:
                                int a = musiclist.size() / 10;
                                int c=musiclist.size()%10;
                                int b=a*10+10;
                                int n1 = (int) (Math.random()*b);
                                if (n1>=musiclist.size()){
                                    n1=n1-(c+1);
                                }
                                number = n1;
                                sendBroadcastOnCommand(MusicService.COMMAND_PLAY);
                                handler.sendEmptyMessage(PROGRESS_RESET);
                                play.setImageResource(R.drawable.play);
                                break;
                            case 203:
                                sendBroadcastOnCommand(MusicService.COMMAND_PLAY);
                                handler.sendEmptyMessage(PROGRESS_RESET);
                                play.setImageResource(R.drawable.play);
                                break;
                            case 204:
                                number = intent.getIntExtra("number", 0);
                                if (number == Musiclist.getMusiclist().size() - 1) {
                                    number = 0;
                                    sendBroadcastOnCommand(MusicService.COMMAND_PLAY);
                                } else {
                                    sendBroadcastOnCommand(MusicService.COMMAND_NEXT);
                                }
                                handler.sendEmptyMessage(PROGRESS_RESET);
                                play.setImageResource(R.drawable.play);
                                break;
                        }
                        break;
                    default:
                        break;
                }
            }
        }
    }


    //屏蔽物理键调节音量是系统弹出来的Toast
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_DOWN) {
            am.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_LOWER, 0);
        } else if (event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_UP) {
            am.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_RAISE, 0);
        }
        return true;
    }

    //格式化音乐时间
    private String formatTime(int mesc) {
        int minute = mesc / 1000 / 60;
        int second = mesc / 1000 % 60;
        String minutestring;
        String secondstring;
        if (minute < 10) {
            minutestring = "0" + minute;
        } else {
            minutestring = "" + minute;
        }
        if (second < 10) {
            secondstring = "0" + second;
        } else {
            secondstring = "" + second;
        }
        return minutestring + ":" + secondstring;
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.play:
                switch (status) {
                    case MusicService.STATUS_PLAYING:
                        sendBroadcastOnCommand(MusicService.COMMAND_PAUSE);
                        mCircleAnimator.pause();
                        break;
                    case MusicService.STATUS_PAUSED:
                        sendBroadcastOnCommand(MusicService.COMMAND_RESUME);
                        mCircleAnimator.resume();
                        break;
                    case MusicService.STATUS_BEGIN:
                        sendBroadcastOnCommand(MusicService.COMMAND_RESUME);
                        mCircleAnimator.start();
                        break;
                    case MusicService.COMMAND_STOP:
                        sendBroadcastOnCommand(MusicService.COMMAND_PLAY);
                        mCircleAnimator.start();
                }
                break;
            case R.id.previous:
                if(playmode==202){
                    int a = musiclist.size() / 10;
                    int c=musiclist.size()%10;
                    int b=a*10+10;
                    int n1 = (int) (Math.random()*b);
                    if (n1>=musiclist.size()){
                        n1=n1-(c+1);
                    }
                    number = n1;
                    sendBroadcastOnCommand(MusicService.COMMAND_PLAY);
                    handler.sendEmptyMessage(PROGRESS_RESET);
                    play.setImageResource(R.drawable.play);
                }else {
                    sendBroadcastOnCommand(MusicService.COMMAND_PREVIOUS);
                }
                mCircleAnimator.start();
                break;
            case R.id.stop:
                sendBroadcastOnCommand(MusicService.COMMAND_STOP);
                mCircleAnimator.end();
                break;
            case R.id.next:
                if(playmode==202){
                    int a = musiclist.size() / 10;
                    int c=musiclist.size()%10;
                    int b=a*10+10;
                    int n1 = (int) (Math.random()*b);
                    if (n1>=musiclist.size()){
                        n1=n1-(c+1);
                    }
                    number = n1;
                    sendBroadcastOnCommand(MusicService.COMMAND_PLAY);
                    handler.sendEmptyMessage(PROGRESS_RESET);
                    play.setImageResource(R.drawable.play);
                }else {
                    sendBroadcastOnCommand(MusicService.COMMAND_NEXT);
                }
                mCircleAnimator.start();
                break;
            case R.id.head:
                Intent in1 = new Intent();
                in1.putExtra("Zhuc", Zhuc);
                in1.setClass(MainActivity.this, MenuActivity.class);
                startActivity(in1);
                break;
            case R.id.sel:
                Intent in2 = new Intent();
                in2.putExtra("theme", theme);
                in2.setClass(MainActivity.this, SelectActivity.class);
                startActivity(in2);
                break;
        }
    }

    private void initSeekBarHandler() {
        handler = new Handler() {
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case PROGRESS_INCREASE:
                        if (Seekbar.getProgress() < duration) {
                            //进度条前进一秒
                            Seekbar.setProgress(seekbartime);
                            //seekBar.incrementProgressBy(1000);
                            handler.sendEmptyMessageDelayed(PROGRESS_INCREASE, 1000);
                            //修改显示当前进度的文本
                            timenow.setText(formatTime(seekbartime));
                            seekbartime += 1000;
                        }
                        break;
                    case PROGRESS_PAUSE:
                        handler.removeMessages(PROGRESS_INCREASE);
                        break;
                    case PROGRESS_RESET:
                        //重置进度条画面
                        handler.removeMessages(PROGRESS_INCREASE);
                        Seekbar.setProgress(0);
                        time.setText("00:00");
                        break;
                }
            }
        };
    }

    //Seekbar显示和控制音量
    private void setsound(SeekBar shengyin) {
        am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        //获取最大声音和设置
        int maxsound = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        shengyin.setMax(maxsound);
        //获取当前声音和设置
        int soundnow = am.getStreamVolume(AudioManager.STREAM_MUSIC);
        shengyin.setProgress(soundnow);
        shengyin.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                am.setStreamVolume(AudioManager.STREAM_MUSIC, seekBar.getProgress(), 0);
                int sound = am.getStreamVolume(AudioManager.STREAM_MUSIC);
                seekBar.setProgress(sound);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });


    }

    //显示歌词有关的内部类
    class AsyncDownLoad extends AsyncTask<String, Integer, String> {
        //执行时调用该方法
        @Override
        protected String doInBackground(String... params) {
            String url = null;
            try {
                url = LrcFileDownLoad.getSongLRCUrl(params[0], params[1]);
                lrc_data = LrcFileDownLoad.getHtmlCode(url);

            } catch (Exception e) {
                e.printStackTrace();
            }

            return lrc_data;
        }
        //任务执行前调用该方法
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            tv_lrc.setText("歌词搜索中...");
        }
        //任务执行结束时调用该方法
        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            if (s == null) {
                tv_lrc.setText("没有找到歌词");
            } else {
                try {
                    FileOutputStream outputStream = MainActivity.this.openFileOutput(filename, Context.MODE_PRIVATE);
                    outputStream.write(s.getBytes());
                    outputStream.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                String string = drawLrcWord(filename);
                tv_lrc.setText(string);
            }

        }
    }

    //将歌词保存到本地的方法
    private void get_lrc(Context context) throws IOException {
        String[] files = context.fileList();
        if (musicname != null) {
            filename = musicname + ".lrc";
            List<String> filelist = Arrays.asList(files);
            if (filelist.contains(filename)) {
                String string = drawLrcWord(filename);
                tv_lrc.setText(string);
            } else {
                //判断网络状态
                ConnectivityManager cwjManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo info = cwjManager.getActiveNetworkInfo();
                //网络可用进行下载
                if (info != null && info.isAvailable()) {
                    asyncDownLoad = new AsyncDownLoad();
                    asyncDownLoad.execute(LrcFileDownLoad.LRC_SEARCH_URL, musicname);
                } else {
                    Toast.makeText(MainActivity.this, "当前网络状态不给力，无法下载歌词", Toast.LENGTH_SHORT).show();
                }
            }
        }

    }

    private String drawLrcWord(String filename) {
        String lrc_word = "";
        try {
            Pattern pattern = Pattern.compile("\\[\\d{2}:\\d{2}.\\d{2}\\]");
            File file = new File(getApplicationContext().getFilesDir() + "/" + filename);
            System.out.print(file.getPath());
            BufferedReader reader = new BufferedReader(new FileReader(file));
            String line = "";
            while ((line = reader.readLine()) != null) {
                Matcher m = pattern.matcher(line);
                line = m.replaceAll("");
                line = line.replace("[ti:", "");
                line = line.replace("[ar:", "");
                line = line.replace("[al:", "");
                line = line.replace("[by:", "");
                line = line.replace("[i:", "");
                line = line.replace("j", "");
                line = line.contains("offset") ? "" : line;
                line = line.replace("url", "歌词来源");
                line = line.replace("null", "");
                lrc_word += line + "\n";

            }
            return lrc_word;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    //读取文件，返回String类型
    public String load(String data) {
        FileInputStream in = null;
        BufferedReader reader = null;
        StringBuilder content = new StringBuilder();
        try {
            in = openFileInput(data);           //“data”为文件名
            reader = new BufferedReader(new InputStreamReader(in));
            String line = "";
            while ((line = reader.readLine()) != null) {
                line = line + "\n";               //换行
                content.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return content.toString();
    }

    private void setbgtheme(int bg) {
        switch (bg) {
            case MenuActivity.THEME_MENGLONG:
                main_bg.setBackgroundResource(R.drawable.bg_blur);
                break;
            case MenuActivity.THEME_BINGXUE:
                main_bg.setBackgroundResource(R.drawable.bg_snow);
                break;
            case MenuActivity.THEME_CAISE:
                main_bg.setBackgroundResource(R.drawable.bg_color);
                break;
            case MenuActivity.THEME_HUADUO:
                main_bg.setBackgroundResource(R.drawable.bg_digit_flower);
                break;
            case MenuActivity.THEME_QUNSHANG:
                main_bg.setBackgroundResource(R.drawable.bg_mountain);
                break;
        }
    }

    private void setText(){
        songname.setText(musiclist.get(0).getMusicName());
        artname.setText(musiclist.get(0).getMusicArtist());
        time.setText(formatTime(Integer.parseInt(musiclist.get(0).getMusicDuration())));

    }

}
